%{
AUTHOR: Felipe Arteaga

DATE:  2020--
-------------------------------------------------------------------------
PROJECT:
-------------------------------------------------------------------------
DESCRIPTION:


El periodo de analisis es desde que se manda el SMSPlain con mienduc
(31-Aug-2020 19:50:00, UTC) y se manda el whatsapp 05-Sep-2020 23:35:58 UTC
 O sea una ventana de 5 dias

=========================================================================
%}

clc;clear;close all;fclose('all');
feature('DefaultCharacterSet', 'UTF-8');

pcName=char(java.lang.System.getProperty('user.name'));
if(strcmp(pcName,'felipe'))
    % PC Felipe
    myDir='/Users/felipe/Dropbox/';
    projectDir=[myDir,'git/warnings/'];
    projectDirData=[myDir,'projects/warnings/'];
    addpath(genpath([myDir,'/myMatlabFunctions/']));
end


dirPlots=[projectDir,'/paper/figuresCL/RDs/'];
dirTable=[projectDir,'/paper/tablesCL/'];

dirData=[projectDirData,'/data/chile/'];

%% Load data:
anho=2020;
anhoStr=sprintf('%i',anho);

load([dirData,anhoStr,'/inputRD'],'dataRD','feeCats1','simceCats','carosCat','gratisCat','buenosCat','malosCat','descRadios','oferta','distanciasG')

dic=struct;

dic.('treatedSMSPlain')='Received SMS';
dic.('intendedSMSPlain')='Assigned to SMS';
dic.('riskSMSPlain')='Predicted placement risk';
dic.('schoolsAddedPreSPPreW')='Schools added (5 days window)';


%% RD

restrToAll=dataRD.riskSMSPlain>0.01&dataRD.pobSMSPlain==1;
subpobs=cell(5,3);
subpobs(1,:)={'All',            restrToAll,'all'};
subpobs(2,:)={'Vulnerable',   restrToAll&dataRD.esSep==1,'sep'};
subpobs(3,:)={'Non-vulnerable',      restrToAll&dataRD.esSep==0,'noSep'};
subpobs(4,:)={'PK',    restrToAll&dataRD.grade==-1,'pk'};
subpobs(5,:)={'9th',restrToAll&dataRD.grade==9,'9th'};
subpobs(6,:)={'Voluntary',   restrToAll&dataRD.voluntary==1,'sep'};
subpobs(7,:)={'Non-voluntary',      restrToAll&dataRD.voluntary==0,'noSep'};
subpobs(8,:)={'Unique child',            restrToAll&dataRD.pobSMSPlain_uniqueChild,'uniqCh'};



data=dataRD(:,{'treatedSMSPlain','riskSMSPlain','schoolsAddedPreSPPreW'});
inAnyPob=false(height(data),1);


regressions={'First stage (SMS received)','fs';'ITT','itt';'IV*','iv'};

commands=cell(size(subpobs,1),2);
counter=1;
for p=1:size(subpobs,1)
    
    
    data.(sprintf('subpop%i',p))=subpobs{p,2};
    inAnyPob=inAnyPob|subpobs{p,2};
    
    commands(counter,:)={sprintf('fs_%i',p),sprintf('rdrobust treatedSMSPlain riskSMSPlain if subpop%i==1, c(.3)  p(2) h(.28 .68)',p)};counter=counter+1;
    commands(counter,:)={sprintf('itt_%i',p),sprintf('rdrobust schoolsAddedPreSPPreW riskSMSPlain if subpop%i==1, c(.3)  p(2) h(.28 .68)',p)};counter=counter+1;
    commands(counter,:)={sprintf('iv_%i',p),sprintf('rdrobust schoolsAddedPreSPPreW riskSMSPlain if subpop%i==1, c(.3)  p(2) h(.28 .68) fuzzy(treatedSMSPlain)',p)};counter=counter+1;

    
end

data=data(inAnyPob,:);
res=stataCommand(commands,data);






%%
head=subpobs(:,1)';

cantPobs=(size(subpobs,1));
cantRegs=(size(regressions,1));

matrix_nl=nan(cantRegs,cantPobs);
matrix_nr=nan(cantRegs,cantPobs);
matrix_b=nan(cantRegs,cantPobs);
matrix_sd=nan(cantRegs,cantPobs);
matrix_pOrder=nan(cantRegs,cantPobs);
cell_pl=cell(cantRegs,cantPobs);
cell_pr=cell(cantRegs,cantPobs);


for p=1:cantPobs
    for r=1:cantRegs
        
        res_i=res.(sprintf('%s_%i',regressions{r,2},p));
        
        % Beta
        matrix_b(r,p)=res_i.tau_cl;
        % Sd Beta
        matrix_sd(r,p)=res_i.se_tau_cl;
        
        % N
        matrix_nl(r,p)=res_i.N_h_l;
        matrix_nr(r,p)=res_i.N_h_r;
        
        figure
        a=plotRD(res_i,dataRD,subpobs{p,2});
        
        
        easyExport([dirPlots,sprintf(sprintf('%i_%s_%s',anho,regressions{r,2},subpobs{p,3}))]);
        
        
    end
end

%%

matTable=[matrix_b;matrix_nl(end,:);matrix_nr(end,:)];
matTable_sd=[matrix_sd;nan(2,size(matrix_sd,2))];

opt=struct;
opt.note='*Treated status is defined as "SMS received", what is different than ``seen''''.';
opt.header=head;
opt.stderrs=mat2cellstr(matTable_sd,'conParentesis',true,'precisionDecimal','%.3f');
opt.primeracolumna=[regressions(:,1);{'NL';'NR'}];
%opt.stars=getStars(matTable,matTable_sd);
opt.addColumnNumber=true;
opt.columnafantasma=[1 3 5 7];
opt.filafantasma=[3];
opt.title='(Plain SMS effect) Outcome: schools added in 5 days window';
opt.panel={0,'A. RD'};
opt.alignmentFirstCol={'L{3cm}'};
opt.adjust=true;
opt.file=sprintf('%s%i_tableSMSPlain',dirTable,anho);
tabla=cell2latex(mat2cellstr(matTable,'precisionDecimal','%.3f','revisarFilas',true),'opts',opt);
compileLatex(tabla)
